const Member = require('../../model/member')

//判断是否在群内
exports.isGroup = async (uid, gid) => {

    try {
        var user =await Member.find({
            groupId: gid,
            userId: uid
        })
    } catch (error) {
        return error
    }
    console.log(user);
    if (user.length > 0) {
        return true
    } else {
        return false
    }
}

//获取所有群
exports.getGroup = async (uid, res) => {
    try {
        var data = Member.find({ userId: uid }).select({ groupId: 1 })
    } catch (error) {
        return res.send({
            status: 500
        })
    }
    res.send({
        status: 200,
        data
    })
}

exports.adduser = async (gid, userlist, res) => {
    try {
        for (let i = 0; i < userlist.length; i++) {
            var data = await Member.create({ groupId: gid, userId: userlist[i].id})
        }

    } catch (error) {
        return res.send({
            status: 400
        })
    }
    res.send({
        status: 200
    })
}

exports.ismygroup = async (id, res) => {
    try {
        var a = await Member.find({ userId: id }).populate('groupId')
        // console.log(a);
        var data = []
        a.forEach(item => {
            data.push({ groupId: item.groupId._id, avatar: item.groupId.cover, name: item.groupId.name,time:item.time })
        })
    } catch (error) {
        console.log(error);
        return res.send({
            status: 400
        })
    }
    res.send({
        status: 200,
        data
    })

}


// 获取群成员
exports.getGroupUser = async (id,res)=>{
    try {
         var user = await Member.find({groupId:id}).populate('userId')
        var data = []
        user.forEach(item=>{
            data.push({
                id:item.userId._id,
                avatar:item.userId.avatar,
                name:item?.name||item.userId.name,
                shield:item.shield
            })
        })
    } catch (error) {
        return res.send({
          status:400
        })
    }
    res.send({
      status:200,
      data
    })
   
}
exports.updatamember = async (uid,gid,obj,res)=>{
    try {
        await Member.updateOne({userId:uid,groupId:gid},obj)
    } catch (error) {
        return res.send({
          status:400
        })
    }
    res.send({
      status:200
    })
}

exports.deluser = async (uid,gid,res)=>{
    try {
        await Member.deleteOne({groupId:gid,userId:uid})
    } catch (error) {
        return res.send({
          status:400
        })
    }
    res.send({
      status:200
    })
}



